$(function () {
  /* 获取id */
  const seach = location.search;
  const seachObj = new URLSearchParams(seach);
  const id = seachObj.get('id');
  //console.log(id);

  /* 文章详细内容 */
  $.ajax({
    method: 'get',
    url: 'http://localhost:8080/api/v1/index/article',
    data: { id },
    success: (res) => {
      // console.log(res);
      //渲染数据
      const htmlStr = template('article', res.data);
      $('.article').html(htmlStr);
    }
  })


  /* 评论列表 */
  $.ajax({
    method: 'get',
    url: 'http://localhost:8080/api/v1/index/get_comment',
    data: { articleId: id, },
    success: (res) => {
      // console.log(res);
      const htmlStr = template('comment', res);
      $('.mycomment').html(htmlStr);
    }
  })


  /* 点击按钮发表评论 */
  $('.comment_sub').click((e) => {
    e.preventDefault();
    //获取数据
    const author = $('.comment_name').val();
    const content = $('.comment_input').val();
    //console.log(name, input);
    if (author.length == 0 || content.length == 0) {
      return alert('用户名和评论内容不能为空');
    }

    /* 发送请求 */
    $.ajax({
      method: 'post',
      url: 'http://localhost:8080/api/v1/index/post_comment',
      data: { author, content, articleId: id, },
      success: (res) => {
        console.log(res);
        if (res.code == 201) {
          alert(res.msg);
          window.location.reload();
        }
      }
    })
  });

  /* 热门模板 */
  $.ajax({
    method: 'get',
    url: 'http://localhost:8080/api/v1/index/rank',
    data: {},
    success: (res) => {
      //console.log(res);
      const htmlStr = template('rank', res);
      $('.hotrank_list').html(htmlStr);
    }
  })


  /* 最新评论 */
  $.ajax({
    method: 'get',
    url: 'http://localhost:8080/api/v1/index/latest_comment',
    data: {},
    success: (res) => {
      console.log(res);
      const htmlStr = template('newComment', res);
      $('.comment_list').html(htmlStr);
    }
  })

  /* 焦点关注 */
  $.ajax({
    method: 'get',
    url: 'http://localhost:8080/api/v1/index/attention',
    data: {},
    success: (res) => {
      //console.log(res);
      const htmlStr = template('guanzhuList', res);
      $('.guanzhu_list').html(htmlStr);
    }
  })
});